
//
//  CollectViewController.swift
//  1604_LimitFree
//
//  Created by 千锋 on 16/9/29.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

class CollectViewController: LFNavViewController {
    //数据源
    private var dataArray:NSMutableArray?
    //滚动视图
    private var scrollView:UIScrollView?
    //是否删除状态
    private var isDelete = false
    //分页控件
    private var pageCtrl:UIPageControl?

    override func viewDidLoad() {
        super.viewDidLoad()
        //创建导航
        createMyNav()
        //创建scrollView
        automaticallyAdjustsScrollViewInsets = false
        scrollView = UIScrollView(frame:CGRectMake(0, 64, kScreenWidth, kScreenHeight-64) )
        scrollView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        scrollView?.pagingEnabled = true
        view.addSubview(scrollView!)
                //分页控件
        pageCtrl = UIPageControl(frame:CGRectMake(80, kScreenHeight-60, 20, 200))
        pageCtrl?.pageIndicatorTintColor = UIColor.blackColor()
        view.addSubview(pageCtrl!)

    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        //查询数据
        let dbManager = LFDBManager()
        dbManager.searchAllCollectData { (array) in
            self.dataArray = NSMutableArray(array: array)
            //显示UI
            dispatch_async(dispatch_get_main_queue()) {
                self.showCollectData()
            }
            
        }

    }
    //显示收藏的数据
    func showCollectData(){
        //清空之前的子视图
        for tmpView in (scrollView?.subviews)!{
            if tmpView.isKindOfClass(CollectButton){
                tmpView.removeFromSuperview()
            }
        }
        if dataArray?.count>0{
            
            let cnt = dataArray?.count
            
            let colNum = 3  //按钮的宽度
            let btnW:CGFloat = 80
            let btnH:CGFloat = 100
            let offsetX:CGFloat = 30
            let spaceX = (kScreenWidth-CGFloat(colNum)*btnW-offsetX*2-20)/CGFloat(colNum-1)//横向的间距
            let offsetY:CGFloat = 120-64//第一行y值
            let spaceY:CGFloat = 80//行间距
            
            for i in 0..<cnt!{
                
                let page = i/9 //先计算页书
                //计算按钮的航和列
                let rowAndCol = i%9
                let row = rowAndCol/colNum
                let col = rowAndCol%colNum
                let btnX = offsetX+CGFloat(col)*(btnW+spaceX)+CGFloat(page)*kScreenWidth
                let btnY = offsetY+CGFloat(row)*(btnH+spaceY)
                
                let btn = CollectButton(frame: CGRectMake(btnX, btnY, btnW, btnH))
                //显示数据
                btn.model = dataArray![i] as? CollectModel
                //设置删除状态
                btn.isDelete = isDelete
                scrollView!.addSubview(btn)
                //添加点击事件
                btn.addTarget(self, action: #selector(CollectViewController.clickBtn(_:)), forControlEvents: .TouchUpInside)
                //设置代理
                btn.delegate = self
                //序号
                btn.btnIndex = i
                
            }
            //设置滚动范围
            var pageCnt = cnt!/9+1
            if cnt!%9>0{
                pageCnt += 1
            }
            scrollView?.contentSize = CGSizeMake(CGFloat(pageCnt)*kScreenWidth, 0)
            //设置代理
            scrollView?.delegate = self
            //分页控件
            pageCtrl?.numberOfPages = pageCnt
            pageCtrl?.currentPage = 0
        
        }else{
        
            MyUtil.showAlertMsg("还没有收藏的数据", onViewController: self)
        }
    }
    func clickBtn(btn:CollectButton){
        //点击进入详情界面
        if isDelete == false{
        let detailCtrl = DetailViewController()
        detailCtrl.appId = btn.model?.applicationId
        navigationController?.pushViewController(detailCtrl, animated: true)
        }
    }
    //创建导航
    func createMyNav() {
        //编辑
        addNavButton("编辑", target: self, action: #selector(editAction(_:)), isLeft: false)
        //标题
        addNavTitle("我的收藏")
        //返回
        addBackButton()
    }
    func editAction(btn:UIButton){
        //修改文字
        if isDelete == false{
            //进入删除状态
            btn.setTitle("完成", forState: .Normal)
            //显示删除按钮
            for tmpView in (scrollView?.subviews)!{
                if tmpView.isKindOfClass(CollectButton){
                let btn = tmpView as! CollectButton
                    btn.isDelete = true
                }
            }
            //修改属性
            isDelete = true
        }else{
        //退出删除状态回到正常状态
            //修改文字
            if isDelete == true{
                //进入删除状态
                btn.setTitle("编辑", forState: .Normal)
                //显示删除按钮
                for tmpView in (scrollView?.subviews)!{
                    if tmpView.isKindOfClass(CollectButton){
                        let btn = tmpView as! CollectButton
                        btn.isDelete = false
                    }
                }
                //修改属性
                isDelete = false

            
        }
    }
    


    func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

   }
}
//MARK:
extension CollectViewController:CollectButtonDelegate{
    func diddeleteBtnAtIndex(index: Int) {
        //从数据库删除
        let model = dataArray![index] as! CollectModel
        let dbmanager = LFDBManager()
        dbmanager.deleteWithAppId(model.applicationId!) { (flag) in
            if flag == true{
                //从数据源数组删除
            self.dataArray?.removeObjectAtIndex(index)
                //重新显示
                self.showCollectData()
            }else{
                
                MyUtil.showAlertMsg("删除失败", onViewController: self)
            }
        }
        
    }
}
//UIScrollView代理
extension CollectViewController:UIScrollViewDelegate{
    
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        let index = Int(scrollView.contentOffset.x/scrollView.bounds.size.width)
        pageCtrl?.currentPage = index
    }
}